<template>
  <el-container>
    <el-header>
      <el-icon><edit /></el-icon>
      简易学生成绩管理系统
    </el-header>

    <el-form :inline="true" class="search-form">
      <el-form-item label="学号">
        <el-input v-model="snumber" placeholder="精确查询" size="mini"></el-input>
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="name" placeholder="模糊查询" size="mini"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="search">查询</el-button>
        <el-button type="info" size="mini" @click="reset">重置</el-button>
        <el-button type="success" size="mini" @click="addStudent">录入</el-button>
        <el-button type="primary" plain size="mini" @click="download">导出学生成绩</el-button>
      </el-form-item>
    </el-form>

    <el-main>
      <div class="block" v-if="studentList.data.length>0">
        <el-table :data="studentList.data" stripe style="width: 100%">
          <el-table-column fixed prop="snumber" label="学号" min-width="150"></el-table-column>
          <el-table-column prop="name" label="姓名" min-width="150"></el-table-column>
          <el-table-column prop="classes" label="班级" min-width="160"></el-table-column>
          <el-table-column prop="sex" label="性别" min-width="120"></el-table-column>
          <el-table-column prop="cscore" label="c语言成绩" min-width="120"></el-table-column>
          <el-table-column prop="jscore" label="java成绩" min-width="120"></el-table-column>
          <el-table-column prop="dbscore" label="数据库成绩" min-width="120"></el-table-column>
          <el-table-column fixed="right" label="操作" min-width="150">
            <template v-slot="scope">
              <el-button type="primary" size="small" @click="editStudent(scope.row.id)">编辑</el-button>
              <el-button type="danger" size="small" @click="deleteStudent(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination class="block" v-model:currentPage="currentPage" :page-sizes="[2, 5, 10, 20, 40]"
                       :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"
                       @size-change="handleSizeChange" @current-change="handleCurrentChange">
        </el-pagination>
      </div>
      <div class="no-data" v-if="studentList.data.length===0">
        暂无数据，请添加数据
      </div>
    </el-main>
    <StudentInfoDialog v-show="formVisible" :formVisible="formVisible" :name="dialogTitle" :studentId="studentId" @closeDialog="closeDialog"/>
  </el-container>
</template>

<script lang="ts">
import {ref, reactive, defineComponent, onBeforeMount} from 'vue'
import axios from "axios";
import { ElMessageBox, ElMessage } from 'element-plus'
import { Edit } from '@element-plus/icons-vue'
import StudentInfoDialog from "@/components/AddAndEditStudent.vue";
export default defineComponent({
  name: 'App',
  components: {
    Edit,
    StudentInfoDialog
  },
  setup() {
    const total = ref(0)
    let studentList = reactive({data: [] as any[]})
    const currentPage = ref(1)
    const pageSize = ref(2)
    // 获取学生列表
    const getStudentList = (currentPage, pageSize)=>{
      axios.get('/getStudentList', {
        params: {
          currentPage,
          pageSize
        }
      }).then(res=>{
        let data = res.data
        if(data.code===200) {
          studentList.data = data.msg.data || []
          total.value = data.msg.total;
        }
      }).catch(err=>{
        console.log(err)
      })
    }
    onBeforeMount(()=>{
      getStudentList(currentPage.value, pageSize.value);
    })
    // 每页多少条
    const handleSizeChange = (val) => {
      pageSize.value = val;
      if(pageSize.value * currentPage.value > total.value) {
        currentPage.value = Math.ceil(total.value / pageSize.value)
      }
      getStudentList(currentPage.value, pageSize.value);
    }
    // 当前页号
    const handleCurrentChange = (val) => {
      currentPage.value = val;
      getStudentList(currentPage.value, pageSize.value);
    }


    // 查询关键字
    const snumber = ref('') // 学号
    const name = ref('')// 姓名
    const search = ()=> {
      if(snumber.value.trim()) {
        axios.get('/findBySnumber/' + snumber.value).then(res=>{
          let data = res.data
          if(data.code===200) {
            studentList.data = data.msg.data || []
            total.value = data.msg.data.length;
            currentPage.value = 1
          }
        }).catch(err=>{
          console.log(err)
        })
      } else if (name.value.trim()) {
        axios.get('/findByName',{params:{name: name.value}}).then(res=>{
          let data = res.data
          if(data.code===200) {
            studentList.data = data.msg.data || []
            total.value = data.msg.total;
            currentPage.value = 1
          }
        }).catch(err=>{
          console.log(err)
        })
      }
    }
    const reset = () => {
      snumber.value = ''
      name.value = ''
      currentPage.value = 1
      getStudentList(currentPage.value, pageSize.value);
      // console.log('重置')
    }


    // 对话框
    const formVisible = ref(false)
    const dialogTitle = ref('')
    const studentId = ref(-1)
    const closeDialog = (value: boolean)=>{  // 关闭对话框
      studentId.value = -1
      formVisible.value = value
      getStudentList(currentPage.value, pageSize.value);
    }
    // 录入学生信息
    const addStudent = () => {
      console.log('录入学生信息');
      studentId.value = -1
      dialogTitle.value = '录入学生信息'
      formVisible.value = true
    }
    // 导出学生成绩
    const download = ()=>{
      console.log('导出学生成绩')
      axios.get('/exportToExcel', { responseType: 'blob' }).then(res => {
        console.log(res)
        // const blob = new Blob([res.data], {
        //   type: 'application/octet-stream;charset=utf-8'
        // })
        const blob = new Blob([res.data], {
          type: 'application/vnd.ms-excel;charset=utf-8'
        })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `学生成绩单_${decodeURI(
            res.headers['content-disposition'].split('_')[1]
        )}`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        // console.log(res.headers['content-disposition'])
      }).catch(function (error) {
        console.log(error)
      })
    }


    // 编辑学生信息
    const editStudent = (id)=>{
      studentId.value = id
      formVisible.value = true
      dialogTitle.value = '更新学生信息'
    }
    // 删除学生信息
    const deleteStudent = (id)=>{
      ElMessageBox.confirm('此条记录将被永久删除，是否继续？', '警告',{
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        axios.delete('/deleteStudent/'+id ).then(res=>{
          let data = res.data
          if(data.code===200) {
            ElMessage({
              type: 'success',
              message: '删除成功',
            })
            if(currentPage.value!==1 && pageSize.value * currentPage.value > total.value - 1) {
              currentPage.value = Math.ceil(total.value / pageSize.value)
            }
            getStudentList(currentPage.value, pageSize.value);
          } else {
            ElMessage({
              type: 'warning',
              message: '删除失败',
            })
          }
        }).catch(err=>{
          console.log(err)
        })
      }).catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
    }

    return {
      studentList,
      total,
      pageSize,
      handleSizeChange,
      handleCurrentChange,

      snumber,
      name,
      search,
      reset,
      addStudent,
      download,

      editStudent,
      deleteStudent,

      currentPage,
      formVisible,
      dialogTitle,
      studentId,
      closeDialog
    }
  }
});
</script>

<style scoped>
.el-header {
  background-color: #b3c0d1;
  color: var(--el-text-color-primary);
  text-align: center;
  line-height: 60px;
  margin-bottom: 20px;
}
.el-form{
  text-align: center;
}
.el-main {
  background-color: #e9eef3;
  color: var(--el-text-color-primary);
  text-align: center;
  line-height: 30px;
}
.block {
  margin-top: 20px;
}
.no-data {
  margin: 20px 0;
}
</style>

<!--
<script lang="ts">
import {ref, reactive, defineComponent} from 'vue'
import EditStudent from './AddAndEditStudent.vue'
import axios from "axios";
interface student {
  snumber: string, // 学号
  name: string, // 姓名
  class: string, // 班级
  sex: string, // 性别
  cscore: number, // c语言成绩
  jscore: number, // java成绩
  dbscore: number // 数据库成绩
}
export default defineComponent({
  name: "StudentTable",
  components: {
    EditStudent
  },
  setup() {
    let allStudentList: student[] = []
    for(let i=11; i<=30; i++) {
      allStudentList.push({
        snumber: '2010500'+i,
        name: '小红',
        classes: '计算机2班',
        sex: '女',
        cscore: 95,
        jscore: 87,
        dbscore: 88
      })
    }
    let studentList = reactive({data: [] as any[]})
    const total = ref(0)
    total.value = allStudentList.length;
    const pageSize = ref(2)
    const currentPage = ref(1);
    // 前端分页
    const currentData = (pageSize, currentPage)=>{
      if(pageSize * currentPage > total.value) {
        currentPage = 1;
      }
      const endPage = currentPage * pageSize < total.value ? currentPage * pageSize : total.value
      studentList.data = allStudentList.slice((currentPage-1)*pageSize, endPage);
      // console.log(studentList)
    }
    currentData(pageSize.value, currentPage.value);
    // 每页多少条
    const handleSizeChange = (val) => {
      pageSize.value = val;
      currentData(pageSize.value, currentPage.value);
    }
    // 当前页号
    const handleCurrentChange = (val) => {
      currentPage.value = val;
      currentData(pageSize.value, currentPage.value);
    }
    const editStudent = ()=>{
      console.log('编辑学生信息');
      formVisible.value = true
    }
    const deleteStudent = ()=>{
      console.log('删除')
    }

    const formVisible = ref(false)  // 对话框
    const closeDialog = (value: boolean)=>{  // 关闭对话框
      // console.log('关闭对话框', value)
      formVisible.value = value
    }
    return {
      studentList,
      total,
      pageSize,
      currentPage,
      handleSizeChange,
      handleCurrentChange,
      editStudent,
      deleteStudent,
      formVisible,
      closeDialog
    }
  }
})
</script>

-->
